﻿using System;
using System.Collections.Specialized;
using System.Data;
using UFSoft.UBF.Sys.Database;
using UFSoft.UBF.UI.JMF.Controls;
using UFSoft.UBF.UI.JMF.Controls.Adapters;
using UFSoft.UBF.UI.JMF.Engine.Builder;
using UFSoft.UBF.UI.JMF.Interface.View;
using UFSoft.UBF.UI.MD.Runtime;
using UFSoft.UBF.Util.DataAccess;

namespace UFIDA.U9.Cust.PDA.JMFUIPlugIn
{
    public class AddPrintBtnPlugIn : UFSoft.UBF.UI.JMF.Forms.Extend.ExtendedPartBase
    {
        private string _entityType = string.Empty;
        private IPart _part = null;

        public override void AfterInit(IPart part, EventArgs args)
        {
            base.AfterInit(part, args);

            if (part == null) return;
            _part = part;
            _entityType = part.Model.Views[0].Name;
            UFToolbar toolbar = (UFToolbar)_part.GetUFControlByName(_part.TopLevelContainer, "Toolbar2");
            if (toolbar == null)
                toolbar = (UFToolbar)_part.GetUFControlByName(_part.TopLevelContainer, "Toolbar1");

            // 添加分割条
            ToolbarSeparator separator = new ToolbarSeparator();
            toolbar.Controls.Add(separator);
            (toolbar as UFToolbar).Controls.Add(separator);

            // 打印条码按钮
            UFWebButtonAdapter btnBarCodeUsePrint = UIControlBuilder.BuilderToolbarButton(toolbar as IUFContainer, "true", "btnNewPrint", "true", "true",
                70, 28, "100", "", false, false, "", "", new Guid().ToString());
            btnBarCodeUsePrint.Text = "打印条码";
            btnBarCodeUsePrint.Click += new EventHandler(btnNewPrint_Click);
            (toolbar as UFToolbar).Controls.Add(btnBarCodeUsePrint as System.Web.UI.Control);
        }

        public void btnNewPrint_Click(object sender, EventArgs e)
        {
            UICommon.DataCollect(_part);

            IUIRecord focusedRecord = this._part.Model.Views[0].FocusedRecord;
            if (focusedRecord == null) return;

            long mainID = AsLong(focusedRecord["ID"]);
            if (mainID <= 0L) return;

            DataParamList list = new DataParamList();
            list.Add(DataParamFactory.CreateInput("@EntityType", _entityType, DbType.String));
            list.Add(DataParamFactory.CreateInput("@EntityID", mainID, DbType.Int64));
            DataAccessor.RunSP(DatabaseManager.GetCurrentConnection(), "Cust_PDA_GenBarCode", list);

            NameValueCollection nameValues = new NameValueCollection();
            nameValues.Add("EntityType", _entityType);
            nameValues.Add("EntityID", mainID.ToString());
            _part.NavigatePage("Cust.PDA.BarCodePrint", nameValues);
        }

        private long AsLong(object mainID)
        {
            long value = 0L;
            if (mainID == null || mainID == DBNull.Value || string.IsNullOrEmpty(mainID.ToString()))
                return value;
            long.TryParse(mainID.ToString(), out value);
            return value;
        }
    }
}
